package com.yhsoft.common.service;

import com.yhsoft.common.utils.Md5Utils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static java.lang.System.out;

/**
 * @author: yyyyyyyh
 * @create: 2024-01-08
 * @Version 1.0
 **/
public class FuSiLingApiService {

    private static String testApi = "http://testopenapi.fsiling.com";
    private static final CloseableHttpClient httpClient = HttpClients.createDefault();
    private static final String partnerId = "100219";
    private static final String code = "q80JSPZdmNPI";
    private static final String secretKey = "xcSjqJ9Ub4Tu";

    @NotNull
    private static HttpPost modifyCommPostHeader(List<BasicNameValuePair> nameValuePairs, String target) throws UnsupportedEncodingException {
        long timestamp = System.currentTimeMillis();
        String sign = Md5Utils.getMD5Code((partnerId + timestamp + code).toLowerCase() + secretKey).toLowerCase();

        out.println("请求地址： " + target);
        HttpPost httpPost = new HttpPost(target);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        nameValuePairs.add(new BasicNameValuePair("partnerId", partnerId));
        nameValuePairs.add(new BasicNameValuePair("code", code));
        nameValuePairs.add(new BasicNameValuePair("timestamp", String.valueOf(timestamp)));
        nameValuePairs.add(new BasicNameValuePair("sign", sign));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        return httpPost;
    }

    /**
     * 账户余额查询
     * @return
     */
    public static String balanceApi() throws IOException {
        String targetApi = testApi + "/api/partner/balance";
        HttpPost httpPost = modifyCommPostHeader(new ArrayList<>(), targetApi);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } finally {
            response.close();
        }
    }

}
